<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>6.命令模式</title>
</head>
<body>
	有时候需要向某些对象发送请求，但是并不知道请求的接收者是谁，也不知道被请求的操作是什么，<br><br>
	此时希望用一种松耦的方式来设计软件，是的请求发送着和请求接收者能够消除彼此之间的耦合关系。<br><br>



	<button id="button1">点击按钮1</button>
	<button id="button2">点击按钮2</button>
	<button id="button3">点击按钮3</button>
</body>
<script type="text/javascript">


	/* 模拟传统面向对象语言 */
	var button1 = document.getElementById('button1');
	var button2 = document.getElementById('button2');
	var button3 = document.getElementById('button3');

	var setCommand = function(button,command){
		button.onclick = function(){
			command.execute();
		}
	}

	var MenuBar = {
		refresh : function(){
			console.log('刷新菜单目录');
		}
	}


	var subMenu = {
		add : function(){
			console.log('增加子菜单');
		},
		del:function(){
			console.log('删除子菜单');
		}
	}

	var RefreshMenuBarCommand = function(receiver){
		this.receiver = receiver;
	};

	RefreshMenuBarCommand.prototype.execute = function() {
		this.receiver.refresh();
	};

	var AddSubMenuCommand = function(receiver){
		this.receiver = receiver;
	};
	AddSubMenuCommand.prototype.execute = function() {
		this.receiver.add();
	};

	var DelSubMenuCommand = function(receiver){
		this.receiver = receiver;
	};
	DelSubMenuCommand.prototype.execute = function() {
		this.receiver.del();
	};

	var refreshMenuBarCommand = new RefreshMenuBarCommand(MenuBar);
	var addSubMenuBarCommand = new AddSubMenuCommand(subMenu);
	var delSubMenuBarCommand = new DelSubMenuCommand(subMenu);

	setCommand(button1,refreshMenuBarCommand);
	setCommand(button2,addSubMenuBarCommand);
	setCommand(button3,delSubMenuBarCommand);



	/* js的命令模式 */
	var RefreshMenuBarCommand = function(receiver){
		return {
			execute:function(){
				receiver.refresh();
			}
		}
	}

	var setCommand = function(button,command){
		button.onclick = function(){
			command.execute();
		}
	}

	var refreshMenuBarCommand = RefreshMenuBarCommand(MenuBar);
	setCommand( button1,refreshMenuBarCommand );


	/* 宏命令---就是执行一堆函数 */
	var closeDoorCommand = {
		execute : function(){
			console.log('关门');
		}
	};

	var openPcCommand = {
		execute : function(){
			console.log('开电脑');
		}
	}

	var openQQCommand = {
		execute : function(){
			console.log('登陆qq');
		}
	}

	var MacroCommand = function(){
		return {
			commandsList : [],
			add : function(command){
				this.commandsList.push(command);
			},
			execute : function(){
				for (var i = 0,command; command = this.commandsList[i++];) {
					command.execute();
				}
			}
		}
	}

	var macroCommand = MacroCommand();

	macroCommand.add( closeDoorCommand );
	macroCommand.add( openPcCommand );
	macroCommand.add( openQQCommand );

	macroCommand.execute();



</script>
</html>